/*
 * Copyright (c) 2017. 深圳掌控网络有限公司. All rights reserved.
 */

package com.yiqi.lottery.feature.mine.presenter;

import android.icu.lang.UProperty;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.*;
import com.suozhang.framework.entity.bo.UserInfoBo;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.ValidatorUtil;
import com.suozhang.framework.utils.logger.Logger;
import com.yiqi.lottery.entity.bo.EditPwdBo;
import com.yiqi.lottery.entity.bo.RegisterBo;
import com.yiqi.lottery.entity.bo.TokenBo;
import com.yiqi.lottery.entity.bo.UploadBo;
import com.yiqi.lottery.feature.login.dependencies.login.DaggerLoginPresenterComponent;
import com.yiqi.lottery.feature.mine.contract.MineContract;
import com.yiqi.lottery.feature.mine.dependencies.mine.DaggerMinePresenterComponent;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.json.JSONObject;

import javax.inject.Inject;
import java.io.File;
import java.text.DecimalFormat;

/**
 *      LIJUWEN
 * @email yiyayiyayaoljw@gmail.com
 * @date 2017/4/11 9:31
 */
public class MinePresenter implements MineContract.Presenter {

    private MineContract.View mView;

    @Inject

    MineContract.Model mModel;



    public MinePresenter(MineContract.View mView) {
        this.mView = mView;
        DaggerMinePresenterComponent.create().inject(this);
    }

    @Override
    public void start() {

    }


    @Override
    public void doGetUserInfo() {


        mModel.getUsertInfo().compose(mView.bindToLife()).subscribe(new Observer<UserInfoBo>() {
            @Override
            public void onSubscribe(Disposable d) {
//                mView.showLoading(d);
            }

            @Override
            public void onNext(UserInfoBo s) {
//                mView.dismissLoading();
                mView.showUserInfoSuccess(s);
            }

            @Override
            public void onError(Throwable e) {
//                mView.dismissLoading();
                mView.showError(e.getMessage());
            }

            @Override
            public void onComplete() {
//                mView.dismissLoading();
            }
        });
    }

    @Override
    public void doUserAuth(String ident_card, String realname, String mobile, String code) {
        if (!ValidatorUtil.isIDCard(ident_card)) {
            T.showShort("身份证格式有误!");
            return;
        }
        if (TextUtils.isEmpty(realname)) {
            T.showShort("真实名称不能为空!");
            return;
        }
        if (!ValidatorUtil.isMobile(mobile)) {
            T.showShort("手机号格式有误!");
            return;
        }
//        if (TextUtils.isEmpty(code)&&code.length()!=6) {
//            T.showShort("验证码格式有误!");
//            return;
//        }

       RegisterBo registerBo=new RegisterBo(mobile,null,ident_card,realname);
        mModel.getUserAuth(registerBo).compose(mView.bindToLife()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                mView.showLoading(d);
            }

            @Override
            public void onNext(String s) {
                mView.showAuthSuccess(s);
                mView.dismissLoading();
            }

            @Override
            public void onError(Throwable e) {
                mView.showError(e.getMessage());
                mView.dismissLoading();
            }

            @Override
            public void onComplete() {
                mView.dismissLoading();
            }
        });
    }

    @Override
    public void doUserSendCode(String mobile) {
        if (!ValidatorUtil.isMobile(mobile)) {
            T.showShort("手机号格式不正确！");
            return;
        }
        mModel.userSendCode(mobile).compose(mView.bindToLife()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                mView.showLoading(d);
            }

            @Override
            public void onNext(String s) {
                mView.showSendCodeSuccess(s);
                mView.dismissLoading();
            }

            @Override
            public void onError(Throwable e) {
                mView.showSendCodeError(e.getMessage());
                mView.dismissLoading();
            }

            @Override
            public void onComplete() {
                mView.dismissLoading();
            }
        });
    }

    @Override
    public void getEditPassword(String oldPassword, String newPassword, String reNewPassword) {
        if (TextUtils.isEmpty(oldPassword)) {
            T.showShort("旧密码不能为空!");
            return;
        }
        if (TextUtils.isEmpty(newPassword)) {
            T.showShort("新密码不能为空!");
            return;
        }
        if (TextUtils.isEmpty(reNewPassword)) {
            T.showShort("请重复输入新密码!");
            return;
        }

        if (!newPassword.equals(reNewPassword)){
            T.showShort("两次输入密码不一致!");
            return;
        }

        EditPwdBo editPwdBo=new EditPwdBo(oldPassword,newPassword,reNewPassword);
        mModel.getEditPassword(editPwdBo).compose(mView.bindToLife()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                mView.showLoading(d);
            }

            @Override
            public void onNext(String s) {
             mView.dismissLoading();
             mView.showEditPwdSuccess(s);
            }

            @Override
            public void onError(Throwable e) {
                mView.dismissLoading();
                mView.showError(e.getMessage());
            }

            @Override
            public void onComplete() {
                mView.dismissLoading();
            }
        });
    }


    @Override
    public void postQiniuToken() {
        mModel.getQiniuToken().compose(mView.bindToLife()).subscribe(new Observer<TokenBo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TokenBo s) {
                mView.showQiniuTokenSuccess(s);
            }

            @Override
            public void onError(Throwable e) {
                mView.showError(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void editUserInfo(Integer userId, String avatar) {

        if (TextUtils.isEmpty(avatar)){
            mView.showSendCodeError("请选择头像！");
            return;
        }
        UserInfoBo userInfoBo=new UserInfoBo();
        userInfoBo.setAvatar(avatar);
          mModel.editUserInfo(userId,userInfoBo).compose(mView.bindToLife()).subscribe(new Observer<UserInfoBo>() {
              @Override
              public void onSubscribe(Disposable d) {
                  mView.showLoading(d);
              }

              @Override
              public void onNext(UserInfoBo s) {
                  mView.dismissLoading();
                  mView.showUserInfoSuccess(s);
              }

              @Override
              public void onError(Throwable e) {
                  mView.dismissLoading();
                  mView.showError(e.getMessage());
              }

              @Override
              public void onComplete() {
                  mView.dismissLoading();
              }
          });
    }

    @Override
    public void editNick(Integer userId, String username) {
        if (TextUtils.isEmpty(username)){
            mView.showSendCodeError("请输入昵称！");
            return;
        }
        UserInfoBo userInfoBo=new UserInfoBo();
        userInfoBo.setUsername(username);
        mModel.editUserInfo(userId,userInfoBo).compose(mView.bindToLife()).subscribe(new Observer<UserInfoBo>() {
            @Override
            public void onSubscribe(Disposable d) {
                mView.showLoading(d);
            }

            @Override
            public void onNext(UserInfoBo s) {
                mView.dismissLoading();
                mView.showUserInfoSuccess(s);
            }

            @Override
            public void onError(Throwable e) {
                mView.dismissLoading();
                mView.showError(e.getMessage());
            }

            @Override
            public void onComplete() {
                mView.dismissLoading();
            }
        });
    }

    @Override
    public void uploadHead(String url,String token) {
        if (TextUtils.isEmpty(url)){
            T.showShort("请选择图片！");
            return;
        }
          upload(url,token);

    }


    public void upload(String url,String token){
        File file = new File(url);

        Configuration config = new Configuration.Builder().zone(FixedZone.zone2).build();
        UploadManager uploadManager = new UploadManager(config);
        uploadManager.put(file, file.getName(), token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response)  {

                if(info.isOK()) {
                    UploadBo uploadBo = JSON.parseObject(response.toString(), UploadBo.class);
                    Logger.d(uploadBo.toString());
                    mView.showUploadHashSuccess(uploadBo.getKey());

                    T.showShort("上传成功!");
                } else {
                    T.showShort("上传失败!");
                }
            }

        },  new UploadOptions(null, null, false,
                new UpProgressHandler(){
                    public void progress(String key, double percent){
                        T.showShort("正在上传中"+getTwoDecimal(percent*100)+"%");
                    }
                },null));
    }
    /**+
     * 将数据保留两位小数
     */
    private double getTwoDecimal(double num) {
        DecimalFormat dFormat=new DecimalFormat("#.00");
        String yearString=dFormat.format(num);
        Double temp= Double.valueOf(yearString);
        return temp;
    }
}
